package com.xzixi.websocket.interceptablewebsocketdemo.websocket;

import com.xzixi.websocket.interceptablewebsocket.interceptor.FromClientInterceptor;
import com.xzixi.websocket.interceptablewebsocket.util.MessageFromClient;
import com.xzixi.websocket.interceptablewebsocketdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.messaging.StompSubProtocolHandler;

import java.security.Principal;

/**
 * @author 薛凌康
 */
public class SessionIdUnRegistryInterceptor implements FromClientInterceptor {

    @Autowired
    private SessionIdRegistry sessionIdRegistry;

    @Override
    public void postHandle(WebSocketSession session, Principal principal, MessageFromClient message, MessageChannel outputChannel, StompSubProtocolHandler handler) {
        User user = (User) session.getAttributes().get("user");
        if (user==null) {
            return;
        }
        if ("DISCONNECT".equals(message.getType())) {
            String username = user.getUsername();
            String sessionId = session.getId();
            sessionIdRegistry.unRegisterSessionId(username, sessionId);
        }
    }

}
